import fs from "fs";
import path from "path";
import readline from "readline";
import fse from "fs-extra";
import { DIST_FOLDER_NAME } from "../config/const";
import { formatNow, getYesterdayLogFileName } from "../utils";
import EventData from "./event-data";

/**
 * 从一行日志中返回query
 * @param line 一行日志
 * @returns query
 */
export const getQueryFormLogLine = (line = "") => {
  // 获取日志中的url
  const reg = /GET\s\/event.gif\?(.+?)\s/;
  const matchResult = line.match(reg);
  if (matchResult == null) return new URLSearchParams();
  const url = matchResult[1];
  if (typeof url !== "string") return new URLSearchParams();
  const query = new URLSearchParams(url);
  return query;
};

export const analysisLogs = (accessLogPath: string) => {
  const eventData = new EventData();
  return new Promise((resolve) => {
    console.log("----------- 分析日志 开始 -----------");
    console.log("当前的时间", formatNow());

    // 日志文件
    const logFile = path.join(
      accessLogPath,
      DIST_FOLDER_NAME,
      getYesterdayLogFileName(),
    );

    fse.ensureFileSync(logFile);

    // 逐行读取文件
    const readStream = fs.createReadStream(logFile);
    const rl = readline.createInterface({
      input: readStream,
    });

    rl.on("line", (line) => {
      if (!line) return;
      const query = getQueryFormLogLine(line);
      const ip = line.split(" ")[0];
      if (query.get("label") == null || query.get("label") == "") {
        return;
      }
      eventData.addView(ip, {
        label: query.get("label") as string,
      });
    });

    rl.on("close", () => {
      const result = eventData.getResult();
      resolve(result);
    });
  });
};
